What is format?
The 'format' npm package is designed to provide string formatting capabilities similar to the sprintf function in C or Python's str.format(). It allows users to embed variables inside a string template with a specific format, making it easier to generate formatted messages or strings dynamically.
What are format's main functionalities?
String substitution
This feature allows for simple substitution of strings into a template. The '%s' specifier is replaced by the 'World' string, resulting in 'Hello, World'.
"Hello, %s".format('World')
Number formatting
Enables formatting of numbers with fixed decimal places. Here, '%.2f' formats the number to two decimal places, resulting in 'Your balance is $123.46'.
"Your balance is $%.2f".format(123.456)
JSON object substitution
Allows embedding JSON objects directly into the string. '%j' is replaced with the JSON string representation of the object, producing a string like '{"name":"John","age":30}'.
"%j".format({name: 'John', age: 30})
Other packages similar to format
sprintf-js
Provides similar functionality to 'format' with additional support for positional arguments and a wider range of format specifiers. It's more closely aligned with the sprintf function in C.
string-template
Offers a simpler approach to string formatting, using named placeholders instead of format specifiers. It's more intuitive for basic use cases but lacks the advanced formatting options available in 'format'.
format
printf, sprintf, and vsprintf for JavaScript
Installation
npm install format
The code works in browsers as well, you can copy these functions into your project
or otherwise include them with your other JavaScript.
Usage
var format = require('format')
, printf = format.printf
, vsprintf = format.vsprintf
// or if you want to keep it old school
, sprintf = format
// Print 'hello world'
printf('%s world', 'hello')
var what = 'life, the universe, and everything'
format('%d is the answer to %s', 42, what)
// => '42 is the answer to life, the universe, and everything'
vsprintf('%d is the answer to %s', [42, what])
// => '42 is the answer to life, the universe, and everything'
Supported format specifiers: b, c, d, f, o, s, x, and X.
See man 3 printf
or man 1 printf
for details.
Precision is supported for floating point numbers.
License
Copyright 2010 - 2014 Sami Samhuri sami@samhuri.net
MIT license